package com.javayh.oauth2.server.conf.service;

import com.google.common.collect.Lists;
import com.javayh.oauth.domain.TbPermission;
import com.javayh.oauth.domain.TbUser;
import com.javayh.oauth2.server.service.TbPermissionService;
import com.javayh.oauth2.server.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 自定义用户认证与授权
 * </p>
 *
 * @version 1.0.0
 * @author Dylan-haiji
 * @since 2020/4/5
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private TbUserService tbUserService;

	@Autowired
	private TbPermissionService tbPermissionService;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		TbUser tbUser = tbUserService.getByUsername(username);
		List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
		if (tbUser != null) {
			// 获取用户授权
			List<TbPermission> tbPermissions = tbPermissionService
					.selectByUserId(tbUser.getId());

			// 声明用户授权
			tbPermissions.forEach(tbPermission -> {
				if (tbPermission != null && tbPermission.getEnname() != null) {
					GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
							tbPermission.getEnname());
					grantedAuthorities.add(grantedAuthority);
				}
			});
		}
		return new User(tbUser.getUsername(), tbUser.getPassword(), grantedAuthorities);
	}

}
